package com.yinhai.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.lz.util.Utils;
import com.lz.views.LoadingDialog;
import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.ContactsUser;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.Util;

/**
 * BFContactsPhoneActivity （通讯录备份）
 * 
 * @author lz
 */
public class BFContactsPhoneActivity extends Activity {
	private ContactUserServiceImpl contactUserService;
	private List<ContactsUser> list;
	private AQuery aq = null;
	private BFContactsPhoneActivity thisRef;
	private LoginConfig log = null;
	 private SharedPreferences sharedPreferences;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contacts_phone);
		thisRef = this;
		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		aq = new AQuery(this);

		contactUserService = new ContactUserServiceImpl(thisRef);

		log = LoginConfigUtil.getConfig(thisRef);
		aq.id(R.id.relout_txlbf).clicked(OnclickTXl);
		aq.id(R.id.relout_txlhf).clicked(OnclickTXLHF);
		aq.id(R.id.relout_txlgl).clicked(OnclickTXLGL);
	}

	OnClickListener OnclickTXLHF = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent it = new Intent(thisRef, HFContactsPhoneActivity.class);
			startActivity(it);

		}
	};

	OnClickListener OnclickTXLGL = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent it = new Intent(thisRef, DelContactsPhoneActivity.class);
			startActivity(it);

		}
	};

	/**
	 * 通讯录备份
	 * 
	 * @param view
	 */
	OnClickListener OnclickTXl = new OnClickListener() {
		@Override
		public void onClick(View v) {
			
			 if (sharedPreferences.contains("bftxlUpdateTime")) {
                 long time = sharedPreferences.getLong("bftxlUpdateTime", 0L);
                 if (System.currentTimeMillis() - time < 1 * 60 * 1000) {
                     Util.showMsg(thisRef, "请勿频繁更新，间隔一分钟后再试");
                     return;
                 }
             }
			Editor editor = sharedPreferences.edit();
			editor.putLong("bftxlUpdateTime", System.currentTimeMillis());
			editor.commit();
			LoadingDialog dialog = new LoadingDialog(thisRef, "正在备份通讯录");
			aq = aq.progress(dialog);
			JSONArray jsonarry = new JSONArray();
			try {
				list = contactUserService.findLocalContact();
				for (int i = 0; i < list.size(); i++) {
					JSONObject json = new JSONObject();
					json.put("name", list.get(i).getName()==null?"":list.get(i).getName());
					json.put("phone", list.get(i).getTelPhone()==null?"":list.get(i).getTelPhone());
					jsonarry.put(json);
				}
			String url = UrlConstant.LOCAL_URI + "backContacts"; // ?phone=" +  log.getUsername() + "&contacts="+
			Map<String, String> params = new HashMap<String, String>();
			params.put("phone", log.getUsername());
			params.put("contacts", jsonarry.toString());
			params.put("phoneNumbers", jsonarry.length() + "");
			
			aq.ajax(url, params, JSONObject.class,
					new AjaxCallback<JSONObject>() {
						@Override
						public void callback(String url, JSONObject json,
								AjaxStatus status) {
								if (json != null) {
									try {
										if (json.getString("flag").equals("1")) {
											Utils.showToast(thisRef, "备份成功");
										}
									} catch (JSONException e) {
										e.printStackTrace();
										Toast.makeText(thisRef, e.getMessage(), Toast.LENGTH_LONG).show();
									}
								}
						}
					});
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(thisRef, e.getMessage(), Toast.LENGTH_LONG).show();
			}

		}
	};

	public void doBack(View view) {
		onBackPressed();
	}

}
